//
//  RDeviceControlView.m
//  iMoive
//
//  Created by 侯伟 on 2021/9/29.
//

#import "RDeviceControlView.h"
#import <Masonry/Masonry.h>
#import <SJBaseVideoPlayer/SJBaseVideoPlayer.h>
#import <SJVideoPlayer/UIView+SJAnimationAdded.h>
#import <LYEmptyView/LYEmptyView.h>
#import <LYEmptyView/UIView+Empty.h>

#import "CLUPnPServer.h"
#import "CLUPnP.h"

@interface RDeviceControlView()<UITableViewDelegate,UITableViewDataSource,CLUPnPServerDelegate>

@property (nonatomic, strong) CLUPnPServer *upd;

@property (nonatomic, strong) UIView *rightContainerView;

@property (nonatomic, strong) UITableView* tableView;

@property (nonatomic, strong) NSArray* devices;

@end

@implementation RDeviceControlView
@synthesize restarted = _restarted;

- (instancetype)initWithFrame:(CGRect)frame{
    if(self = [super initWithFrame:frame]){
        
        self.backgroundColor =  RGBACOLOR(0x00, 0x00, 0x00, 0.7);
        
        CLUPnPServer* updServer = [CLUPnPServer shareServer];
        updServer.searchTime = 5;
        updServer.delegate = self;
        _upd = updServer;
        
        [self setupViews];
    }
    return self;
}

#pragma mark -- SJControlLayer
///
/// 控制层入场
///     当播放器将要切换到此控制层时, 该方法将会被调用
///     可以在这里做入场的操作
///
- (void)restartControlLayer {
    _restarted = YES;
    sj_view_makeAppear(self, YES);
    sj_view_makeAppear(self.rightContainerView, YES);
    
    [self.upd start];
}


///
/// 退出控制层
///     当播放器将要切换到其他控制层时, 该方法将会被调用
///     可以在这里处理退出控制层的操作
///
- (void)exitControlLayer {
    _restarted = NO;
    
    sj_view_makeDisappear(self.rightContainerView, YES);
    sj_view_makeDisappear(self, YES, ^{
        if (!self->_restarted) [self removeFromSuperview];
    });
    
    [self.upd stop];
}

///
/// 控制层视图
///     当切换为当前控制层时, 该视图将会被添加到播放器中
///
- (UIView *)controlView {
    return self;
}

///
/// 当controlView被添加到播放器时, 该方法将会被调用
///
- (void)installedControlViewToVideoPlayer:(__kindof SJBaseVideoPlayer *)videoPlayer {
    if (self.layer.needsLayout ) {
        sj_view_initializes(self.rightContainerView);
    }
    sj_view_makeDisappear(self.rightContainerView, NO);
}

///
/// 当调用播放器的controlLayerNeedAppear时, 播放器将会回调该方法
///
- (void)controlLayerNeedAppear:(__kindof SJBaseVideoPlayer *)videoPlayer {}

///
/// 当调用播放器的controlLayerNeedDisappear时, 播放器将会回调该方法
///
- (void)controlLayerNeedDisappear:(__kindof SJBaseVideoPlayer *)videoPlayer {}

///
/// 当将要触发某个手势时, 该方法将会被调用. 返回NO, 将不触发该手势
///
- (BOOL)videoPlayer:(__kindof SJBaseVideoPlayer *)videoPlayer gestureRecognizerShouldTrigger:(SJPlayerGestureType)type location:(CGPoint)location {
    if ( type == SJPlayerGestureType_SingleTap ) {
        if (!CGRectContainsPoint(self.rightContainerView.frame, location)) {
            if ([self.delegate respondsToSelector:@selector(tappedBlankAreaOnTheControlLayer:)]) {
                [self.delegate tappedBlankAreaOnTheControlLayer:self];
            }
        }
    }
    return NO;
}


///
/// 当将要触发旋转时, 该方法将会被调用. 返回NO, 将不触发旋转
///
- (BOOL)canTriggerRotationOfVideoPlayer:(__kindof SJBaseVideoPlayer *)videoPlayer {
    return NO;
}

#pragma mark -- 搜索协议CLUPnPDeviceDelegate回调
- (void)upnpSearchChangeWithResults:(NSArray<CLUPnPDevice *> *)devices{
    
    NSMutableArray *deviceMarr = [NSMutableArray array];
    for (CLUPnPDevice *device in devices) {
        // 只返回匹配到视频播放的设备
        if ([device.uuid containsString:serviceType_AVTransport]) {
            [deviceMarr addObject:device];
        }
    }
    self.devices = deviceMarr;
    
    [self.tableView reloadData];
}

- (void)upnpSearchErrorWithError:(NSError *)error{
//    NSLog(@"DLNA_Error======>%@", error);
}


#pragma mark --UITableViewDelegate  UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.devices.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CLUPnPDevice *device = [self.devices objectAtIndex:indexPath.row];
    
    UITableViewCell* deviceCell = [tableView dequeueReusableCellWithIdentifier:@"deviceCell" forIndexPath:indexPath];
    deviceCell.selectionStyle = UITableViewCellSelectionStyleNone;
    deviceCell.backgroundColor = UIColor.blackColor;
    deviceCell.selectedBackgroundView.backgroundColor = UIColor.blackColor;
    deviceCell.textLabel.font = FONT_FIT(14);
    deviceCell.textLabel.textColor = COLOR_WHITE;
    deviceCell.indentationLevel = 1; //缩进层级
    deviceCell.indentationWidth = 10.0f; //每次缩进寛
    deviceCell.textLabel.text = device.friendlyName;
    return deviceCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell* deviceCell = [tableView cellForRowAtIndexPath:indexPath];
    deviceCell.textLabel.textColor = UIColor.blueColor;
    
    CLUPnPDevice *device = [self.devices objectAtIndex:indexPath.row];
    if ([self.delegate respondsToSelector:@selector(choiseDeviceOnTheControlLayer:device:)]) {
        [self.delegate choiseDeviceOnTheControlLayer:self device:device];
    }
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell* deviceCell = [tableView cellForRowAtIndexPath:indexPath];
    deviceCell.textLabel.textColor = COLOR_WHITE;
}


- (void)setupViews{
    
    UIView* rightContainerView = [[UIView alloc] initWithFrame:CGRectZero];
    rightContainerView.backgroundColor = UIColor.blackColor;
    rightContainerView.sjv_disappearDirection = SJViewDisappearAnimation_Right;
    [self addSubview:rightContainerView];
    [rightContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.bottom.offset(0);
        make.width.mas_equalTo(self.mas_width).multipliedBy(0.5);
    }];
    _rightContainerView = rightContainerView;
    
    UIView* titleView = [UIView new];
    [rightContainerView addSubview:titleView];
    [titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.offset(0);
        make.height.equalTo(@(PX(32)));
    }];
    
    UILabel* titleLb = [UILabel lableWithFont:FONT_FIT(14) color:COLOR_WHITE text:@"请选择投屏设备"];
    [titleView addSubview:titleLb];
    [titleLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(10);
        make.centerY.equalTo(titleView.mas_centerY);
    }];
    
    //列表
    UITableView* tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = UIColor.blackColor;
    tableView.rowHeight = PX(32);
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.sectionFooterHeight = CGFLOAT_MIN;
    tableView.sectionHeaderHeight = 10;
    tableView.tableFooterView = [UIView new];
    [tableView registerClass:UITableViewCell.class forCellReuseIdentifier:@"deviceCell"];
    [rightContainerView addSubview:tableView];
    _tableView = tableView;
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.top.equalTo(titleView.mas_bottom).offset(0);
    }];
    
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [activityIndicator startAnimating];
    [activityIndicator setHidesWhenStopped:YES];
    
    LYEmptyView* emptyView = [LYEmptyView emptyViewWithCustomView:activityIndicator];
    tableView.ly_emptyView = emptyView;
}
@end
